package cn.lh.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.lh.contants.ErrorCode;
import cn.lh.entity.dto.UserDto;
import cn.lh.entity.req.LoginReq;
import cn.lh.entity.vo.LoginInfoVo;
import cn.lh.exception.BusinessException;
import cn.lh.service.LoginService;
import cn.lh.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @描述:
 * @版权: Copyright (c) 2023
 * @作者: linhong
 * @版本: 1.0.0
 * @创建时间: 2023/12/29
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public LoginInfoVo login(LoginReq req) {
        LambdaQueryWrapper<UserDto> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserDto::getName,req.getUserName())
                .eq(UserDto::getPassword,req.getPassword());
        UserDto dto = userService.getOne(wrapper);
        if(dto == null){
            throw new BusinessException(ErrorCode.USER_NAME_PASSWORD_ERROR);
        }
        LoginInfoVo info = new LoginInfoVo();
        info.setToken(UUID.randomUUID().toString().replace("-",""));
        info.setLoginTime(new Date());
        info.setUserName(req.getUserName());
        info.setUserId(dto.getId());
        redisTemplate.opsForValue().set(info.getToken(),info,120, TimeUnit.MINUTES);
        return info;
    }

    @Override
    public void logout(String userName,String token) {
        if(userName.equals(redisTemplate.opsForValue().get(token))){
            redisTemplate.delete(token);
        }
    }

    @Override
    public void test() {
        System.err.println("start test");
        LoginServiceImpl o = (LoginServiceImpl) AopContext.currentProxy();
        o.test1();
        System.err.println("end test");
    }

    @Override
//    @Async
//    @Transactional
    public void test1() {
        System.err.println("start test1");
        ThreadUtil.sleep(5,TimeUnit.SECONDS);
        System.err.println("end test1");
    }
}
